const express = require("express");
const os = require("os");
const path = require("path");
const child_process = require("child_process");
const upload = require("./src/uploads");
const renameNumber = require("./src/renameNumber");
const writeFile = require("./src/writeFile");
const renamePrefix = require("./src/renamePrefix");
const renameSuffix = require("./src/renameSuffix");
const outputExecl = require("./src/outputExecl");
const outputJson = require("./src/outputJson");
const app = express();
const port = 3000;

// 添加解析JSON请求体的中间件
app.use(express.json());
app.use(express.static(path.join(__dirname)));

//上传文件接口
app.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }
  console.log(
    `文件已上传: ${req.file.originalname}, 存储路径: ${req.file.path}`
  );
});

// 批量重命名并添加序号接口
app.post("/renameNumber", (req, res) => res.json(renameNumber(req.body)));

// 写入文件接口
app.post("/writeFile", (req, res) => res.json(writeFile(req.body)));

// 批量重命名前缀接口
app.post("/renamePrefix", (req, res) => res.json(renamePrefix(req.body)));

// 批量重命名后缀接口
app.post("/renameSuffix", (req, res) => res.json(renameSuffix(req.body)));

// 输出execl接口
app.post("/outputExecl", (req, res) => res.json(outputExecl(req.body)));

// 输出json接口
app.post("/outputJson", (req, res) => res.json(outputJson(req.body)));

app.listen(port, () => {
  // 获取本机IP地址
  const netInfo = os.networkInterfaces(); //网络信息
  let ip = "";
  for (let dev in netInfo) {
    //win7的网络信息中显示为本地连接，win10显示为以太网
    if (dev === "本地连接" || dev === "以太网" || dev === "WLAN") {
      for (let j = 0; j < netInfo[dev].length; j++) {
        if (netInfo[dev][j].family === "IPv4") {
          ip = netInfo[dev][j].address;
          break;
        }
      }
    }
  }
  child_process.exec(`start "" "http://${ip}:${port}"`);
});
